package com.wenwei.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.callback.ConfigInput;
import com.mylhyl.circledialog.params.InputParams;
import com.mylhyl.circledialog.view.listener.OnInputClickListener;
import com.orhanobut.logger.Logger;
import com.wenwei.bean.LoginBean;
import com.wenwei.bean.UserInfoBean;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.Constant;
import com.wenwei.parking.R;
import com.wenwei.upload.ImageService;
import com.wenwei.upload.OssService;
import com.wenwei.upload.PauseableUploadTask;
import com.wenwei.upload.STSGetter;
import com.wenwei.utils.GlideImageLoader;
import com.wenwei.utils.RogerSPUtils;
import com.wenwei.utils.UserStringUtils;
import com.wenwei.view.ContainsEmojiEditText;

import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/21.
 */
public class UserInfoActivity extends BaseActivity {
    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.base_save_tv)
    TextView baseSaveTv;
    @Bind(R.id.user_info_head)
    CircleImageView userInfoHead;
    @Bind(R.id.user_info_name)
    TextView userInfoName;
    @Bind(R.id.user_phone_tv)
    TextView userPhoneTv;
    @Bind(R.id.user_sex_tv)
    TextView userSexTv;
    @Bind(R.id.user_car_info)
    TextView userCarInfo;
    @Bind(R.id.user_car_code)
    TextView userCarCode;


    private OssService ossService;
    private ImageService imageService;
    private static final String bucket = "sharepark";
    private static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";


    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initView() {
        super.initView();
        baseTitle.setText("个人中心");

        initImage();
        initUserInfo();

        ossService = initOSS(endpoint,bucket);
        imageService = new ImageService(ossService);

        userInfoName.addTextChangedListener(new MyTextWatcher());
        userCarInfo.addTextChangedListener(new MyTextWatcher());
        userCarCode.addTextChangedListener(new MyTextWatcher());
    }

    public OssService initOSS(String endpoint, String bucket) {
        //如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        //OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);

        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        credentialProvider = new STSGetter();
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(mContext, endpoint, credentialProvider, conf);
        return new OssService(oss, bucket);

    }

    private WeakReference<PauseableUploadTask> task;
    private void uploadAliImg(String name,String filePate){
        Logger.d("上传前的图片名称："+name);
        task = new WeakReference<>(ossService.asyncMultiPartUpload(name, filePate, new OssService.loadSuccessCallBack() {
            @Override
            public void loadSuccess(final String url) {
                Logger.d("上传成功"+url);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        userHeadImg = url;
                        isChangeUserInfo = true;
                        Glide.with(mContext).load(url).error(R.drawable.icon1).into(userInfoHead);
                        onUserInfoChanged();
                    }
                });

            }
        }));
    }

    private void initImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }


    private Random random = new Random();
    private String currentImg = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 99) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (ImageItem i : images) {
                    Log.d("msg", i.path);
                    if(TextUtils.isEmpty(i.path)){
                        showToast("请选择图片");
                        return;
                    }
                    File file = new File(i.path);
                    String fileName = new Date().getTime()+random.nextInt(100)+file.getName();
                    uploadAliImg(fileName,i.path);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.user_car_code,R.id.user_car_info,R.id.user_info_name,R.id.update_pw,R.id.base_back, R.id.base_save_tv, R.id.user_info_head, R.id.user_sex_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_car_code:
                new CircleDialog.Builder(this)
                        .setCanceledOnTouchOutside(false)
                        .setCancelable(true)
                        .setTitle("车辆号码")
                        .setInputHeight(100)
                        .setWidth(0.8f)
                        .setInputHint("请输入车辆号码")
                        .configInput(new ConfigInput() {
                            @Override
                            public void onConfig(InputParams params) {
                                params.textSize = 38;
                            }
                        })
                        .setNegative("取消", null)
                        .setPositiveInput("确定", new OnInputClickListener() {
                            @Override
                            public void onClick(String text, View v) {
                                userCarCode.setText(text);
                            }
                        })
                        .show();
                break;
            case R.id.user_car_info:
                new CircleDialog.Builder(this)
                        .setCanceledOnTouchOutside(false)
                        .setCancelable(true)
                        .setTitle("车辆信息")
                        .setInputHeight(100)
                        .setWidth(0.8f)
                        .setInputHint("请输入车辆信息")
                        .configInput(new ConfigInput() {
                            @Override
                            public void onConfig(InputParams params) {
                                params.textSize = 38;
                            }
                        })
                        .setNegative("取消", null)
                        .setPositiveInput("确定", new OnInputClickListener() {
                            @Override
                            public void onClick(String text, View v) {
                                userCarInfo.setText(text);
                            }
                        })
                        .show();
                break;
            case R.id.user_info_name:
                new CircleDialog.Builder(this)
                        .setCanceledOnTouchOutside(false)
                        .setCancelable(true)
                        .setTitle("昵称")
                        .setInputHeight(100)
                        .setInputHint("请输入昵称")
                        .configInput(new ConfigInput() {
                            @Override
                            public void onConfig(InputParams params) {
                                params.textSize = 38;
                            }
                        })
                        .setNegative("取消", null)
                        .setPositiveInput("确定", new OnInputClickListener() {
                            @Override
                            public void onClick(String text, View v) {
                                userInfoName.setText(text);
                            }
                        })
                        .show();
                break;
            case R.id.update_pw:
                Bundle forgetBundle = new Bundle();
                forgetBundle.putString("type","forget");
                goActivity(mContext,RegisterActivity.class,forgetBundle);
                break;
            case R.id.base_back:
                if(isChangeUserInfo){
                    new CircleDialog.Builder(UserInfoActivity.this)
                            .setTitle("温馨提示")
                            .setText("您有修改资料未保存，确认关闭？")
                            .setCanceledOnTouchOutside(false)
                            .setPositive("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                   finish();
                                }
                            })
                            .setNegative("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .show();
                }else{
                    finish();
                }
                break;
            case R.id.base_save_tv:
                updateUserInfo();
                break;
            case R.id.user_info_head:
                goActivity(this, ImageGridActivity.class, null, 99);
                break;
            case R.id.user_sex_tv:
                selectSex();
                break;
        }
    }

    private String userHeadImg = "";
    //初始化用户信息
    private void initUserInfo() {
        UserInfoBean ub = RogerSPUtils.getObject(mContext, Constant.SP_USER_USER_RESULT, UserInfoBean.class);
        if (ub != null) {
            userHeadImg = ub.getAvator();
            Glide.with(mContext).load(ub.getAvator()).error(R.drawable.icon1).into(userInfoHead);
            userInfoName.setText(ub.getNickname());
            userPhoneTv.setText(UserStringUtils.getUserPhone(mContext));
            userCarInfo.setText(ub.getCarName());
            userCarCode.setText(ub.getCarNumber());
            if(ub.getSex() == 1){
                userSexTv.setText("男");
            }else if(ub.getSex() == 0){
                userSexTv.setText("女");
            }
        }
    }

    //修改用户资料
    private BaseSubscriber<Object> updateSubscriber;
    private void updateUserInfo(){
        updateSubscriber = new BaseSubscriber<Object>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(Object o) {
                showToast("修改成功");
                Intent intent = new Intent();
                intent.putExtra("image",userHeadImg);
                setResult(RESULT_OK,intent);
                finish();
            }
        };
        try{
//            {
//                "avator": "用户头像,String",
//                    "carName": "车辆信息,String",
//                    "carNumber": "车牌号码,String",
//                    "nickname": "用户昵称,String",
//                    "sex": "用户性别,Integer(男:1;女:0)",
//                    "userId": "用户id,Integer"
//            }
            JSONObject jb = new JSONObject();
            jb.put("avator",userHeadImg);
            jb.put("carName",userCarInfo.getText().toString());
            jb.put("carNumber",userCarCode.getText().toString());
            if(userSexTv.getText().toString().equals("男")){
                jb.put("sex",1);
            }else if (userSexTv.getText().toString().equals("女")){
                jb.put("sex",0);
            }else {
                jb.put("sex",-1);
            }
            jb.put("nickname",userInfoName.getText().toString());
            jb.put("userId", UserStringUtils.getUserId(mContext));
            Logger.d("参数："+jb.toString());
            ApiManager.getInstance().updateUserProfile(updateSubscriber,jb.toString());
        }catch (Exception e){

        }
    }


    private class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d("msg", "beforeTextChanged");

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d("msg", "onTextChanged");
            isChangeUserInfo = true;
            onUserInfoChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d("msg", "afterTextChanged");
        }
    }


    private boolean isChangeUserInfo = false;//是否修改过用户资料
    private void onUserInfoChanged() {
        if (isChangeUserInfo) {
            baseSaveTv.setVisibility(View.VISIBLE);
        }
    }

    OptionsPickerView pvOptions;
    private void selectSex() {
        pvOptions = new OptionsPickerView(this);
        final ArrayList<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        pvOptions.setPicker(sexList);
        pvOptions.setTitle("选择性别");
        pvOptions.setSelectOptions(0);
        pvOptions.setCyclic(false);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                isChangeUserInfo = true;
                onUserInfoChanged();
                userSexTv.setText(sexList.get(options1));
            }
        });
        pvOptions.show();
    }
}
